#!/bin/bash -x

test_pod_dir="$HOME/workspace/pod-workload"

registry_ip_addr=""
registry_port=31313
registry=""

pod_yaml="${test_pod_dir}/auth-pod.yaml"
pod_name="busybox"
pod_container_image_basename="busybox:latest"
pod_runtimeclass="kata-qemu-csv"
pod_container_image_uri=""

usage () {
  set +x
  echo -e "\033[31m
Usage: $0 <-h|<-i <registry-ip-addr>> [-p <registry-port>] [-r <kata-coco-runtimeclass>]>

       -h,--help         Display this help message
       -i,--ip           The ip address of the local registry
       -p,--port         The port number of the local registry
       -r,--runtimeclass Specify the runtimeclass
                         Valid value are shown as following:
                             kata-qemu-coco-dev
                             kata-qemu-csv
                             kata-qemu-csv2
                             kata-qemu-csv3
                         Default is kata-qemu-csv
\033[0m"
  set -x
}

params=$(getopt -o hi:p:r: --long help,ip:,port:,runtimeclass: -- "$@")
if [ $? -ne 0 ]; then
  echo "[Error] cannot parse parameters"
  exit 1
fi

eval set -- "$params"

while true; do
  case "$1" in
  -h|--help)
    usage
    exit 0
    ;;
  -i|--ip)
    registry_ip_addr="$2"
    shift 2
    ;;
  -p|--port)
    registry_port="$2"
    shift 2
    ;;
  -r|--runtimeclass)
    pod_runtimeclass="$2"
    shift 2
    ;;
  --)
    shift
    break
    ;;
  *)
    usage
    exit 1
    ;;
  esac
done

if [ "X${registry_ip_addr}" = "X" ]; then
  usage
  exit 1
fi

registry="${registry_ip_addr}:${registry_port}"
pod_container_image_uri="${registry}/${pod_container_image_basename}"



authenticated_image="docker.io/robertsonhan/busybox-curl:latest"
authenticated_image_namespace="$(echo "${authenticated_image}" | cut -d':' -f1)"
authenticated_image_user="AAAA"
authenticated_image_password="BBBB"
auth_conf_file="${test_pod_dir}/auth-pod.json"

kbs_namespace="trustee-operator-system"
kbs_deployment="trustee-deployment"
kbs_ip_addr="$(kubectl get pods -n ${kbs_namespace} -o wide | \
  grep ${kbs_deployment} | \
  sed "s/^.* \([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\) .*$/\1/g")"
kbs_resource_path="/opt/confidential-containers/kbs/repository"
kbs_key_path="default/containers/auth"

k8s_auth_secret_name="my-cococred"

generate_auth_conf_file () {
  echo "[Generate auth config file]"

  if [ ! -d $(dirname ${auth_conf_file}) ]; then
    mkdir -p $(dirname ${auth_conf_file})
  fi

  cat <<EOF | tee ${auth_conf_file}
{
	"auths": {
		"${authenticated_image_namespace}": {
			"auth": "$(echo ${authenticated_image_user}:${authenticated_image_password} | base64 -w 0)"
		}
	}
}
EOF
}

generate_auth_conf_file

upload_auth_to_kbs () {
  echo "[Upload auth data to kbs]"
  kubectl exec deploy/${kbs_deployment} \
    -c kbs -n ${kbs_namespace} \
    -- mkdir -p "${kbs_resource_path}/$(dirname "${kbs_key_path}")"
  cat ${auth_conf_file} | kubectl exec -i deploy/${kbs_deployment} \
    -c kbs -n ${kbs_namespace} \
    -- tee "${kbs_resource_path}/${kbs_key_path}" > /dev/null
}

upload_auth_to_kbs

generate_k8s_auth_secret () {
  echo "[Generate k8s auth secret]"
  kubectl delete secret "${k8s_auth_secret_name}" || true
  kubectl create secret docker-registry "${k8s_auth_secret_name}" \
    --docker-server="https://${authenticated_image_namespace}" \
    --docker-username="${authenticated_image_user}" \
    --docker-password="${authenticated_image_password}"
}

generate_k8s_auth_secret

generate_pod_yaml () {
  echo "[Generate Pod yaml]"

  if [ ! -d $(dirname ${pod_yaml}) ]; then
    mkdir -p $(dirname ${pod_yaml})
  fi

  cat <<EOF | tee ${pod_yaml}
apiVersion: v1
kind: Pod
metadata:
  name: auth-${pod_name}
  annotations:
    io.containerd.cri.runtime-handler: ${pod_runtimeclass}
    io.katacontainers.config.hypervisor.kernel_params: 'agent.image_registry_auth=kbs:///${kbs_key_path} agent.guest_components_rest_api=resource agent.aa_kbc_params=cc_kbc::http://${kbs_ip_addr}:8080'
spec:
  runtimeClassName: ${pod_runtimeclass}
  containers:
    - name: ${pod_name}-c1
      image: ${pod_container_image_uri}
      imagePullPolicy: Always
      command:
        - sleep
        - infinity
  imagePullSecrets:
    - name: ${k8s_auth_secret_name}
EOF
}

generate_pod_yaml

run_pod () {
  echo "[Run Pod]"
  kubectl delete -f ${pod_yaml} || true
  kubectl apply -f ${pod_yaml}
}

run_pod
